﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading;
using Newtonsoft.Json;

public class GameVersionDataManager
{
    static GameVersionDataManager _Instance;
    public static GameVersionDataManager Instance 
    { 
        get 
        {
            if(_Instance == null) _Instance = new GameVersionDataManager();
            return _Instance;
        } 
    }

    private readonly FileSystemWatcher m_Watcher = new FileSystemWatcher();
    private readonly Timer m_Timer;

    GameVersion m_GameVersion;
    public GameVersion gameVersion => m_GameVersion;

    public static Action onGameVersionChange;

    public GameVersionDataManager()
    {
        m_Timer = new Timer(Update);

        ReadData();
    }

    public void Init()
    {
        //初始化监听
        m_Watcher.BeginInit();
        //设置监听文件类型
        m_Watcher.Filter = "*.json";
        //设置是否监听子目录
        m_Watcher.IncludeSubdirectories = true;
        //设置是否启用监听?
        m_Watcher.EnableRaisingEvents = true;
        //设置需要监听的更改类型(如:文件或者文件夹的属性,文件或者文件夹的创建时间;NotifyFilters枚举的内容)
        m_Watcher.NotifyFilter = NotifyFilters.DirectoryName | NotifyFilters.FileName | NotifyFilters.LastWrite;
        //设置监听的路径
        m_Watcher.Path = ServerConfig.gameVersionConfigDir;
        //注册创建文件或目录时的监听事件
        m_Watcher.Created += new FileSystemEventHandler(watch_changed);
        //注册当指定目录的文件或者目录发生改变的时候的监听事件
        m_Watcher.Changed += new FileSystemEventHandler(watch_changed);
        //注册当删除目录的文件或者目录的时候的监听事件
        m_Watcher.Deleted += new FileSystemEventHandler(watch_changed);
        //当指定目录的文件或者目录发生重命名的时候的监听事件
        m_Watcher.Renamed += new RenamedEventHandler(watch_changed);
        //结束初始化
        m_Watcher.EndInit();
    }

    private void ReadData()
    {
        // 从文件中读取
        var str = System.IO.File.ReadAllText(ServerConfig.gameVersionPath, Encoding.UTF8);
        var gameVersion = JsonConvert.DeserializeObject<GameVersion>(str);
        m_GameVersion = gameVersion;

        onGameVersionChange?.Invoke();
    }

    // 文件变更更新
    private void watch_changed(object sender, FileSystemEventArgs e)
    {
        GameDebug.Log($"版本文件变化：[{e.FullPath}]");
        m_Timer.Change(TimeSpan.FromSeconds(3), Timeout.InfiniteTimeSpan);
    }

    private void Update(object state)
    {
        GameDebug.Log($"ConstDataManager -> Update");
        m_Timer.Change(Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan);

        ReadData();
    }


}

